<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Role;
use App\Repos\RoleRepo;
use App\Repos\MenuRepo;
use App\Models\RoleMenu;
use App\Models\Menu;

class RoleController extends Controller
{
    public function __construct(MenuRepo $menuRepo)
    {
        $this->menu = $menuRepo;
        
    }

    public function index(Request $request)
    {
    	$where = [];
    	$list = Role::where($where)->paginate(10);
    	return view('admin.role.index',compact('list'));
    }

    public function edit($id)
    {
        $data  = Role::find($id);
        $collection = collect();  
        $menus = $this->menu->get_menus($collection,0);
        $roleMenu = RoleMenu::where(['role_id'=>$id])->first();
        $role_menu_arr = [];
        if(object_get($roleMenu,'menu_ids')) {
            $role_menu_arr = explode(',', $roleMenu->menu_ids);    
        }
        $role_permission_arr = [];
        if(object_get($roleMenu,'permission_ids')) {
            $role_permission_arr = explode(',', $roleMenu->permission_ids);    
        }
        //dd($role_menu_arr,$role_permission_arr);
        return view('admin.role.edit',compact('data','menus','role_permission_arr','role_menu_arr'));
    }

    public function store(Request $request)
    {
        $data = $request->only(['name']);
        $flag = Role::create($data);
        if($flag) {
            //return back();
            return redirect('zadmin/role/'.$flag->id.'/edit');
        }
    }

     public function update(Request $request, $id)
    {
        $rs['status'] = false;
        $rs['msg'] = '操作失败';
        $data = $request->except(['_token','_method']);
        $where['id'] = $id;
        $flag = RoleRepo::update($where,$data);
        
        if($flag) {
            $rs['msg'] = '操作成功';
            return redirect('zadmin/role')->with('rs',$rs);    
        } 
        return back();
        
    }

    public function destroy($id)
    {
        Role::destroy($id);
        return back();
    }
}
